Number guessing Game code
#include
#include // for rand() and srand()
#include // for time()
using namespace std;
int main() {
// Initialize random seed
srand(time(0));
int secretNumber = rand() % 100 + 1; // Random number between 1 and 100
int guess;
int attempts = 0;
cout << "Welcome to the Number Guessing Game!" << endl;
cout << "I'm thinking of a number between 1 and 100." << endl;
do {
cout << "Enter your guess: ";
cin >> guess;
attempts++;
if (guess > secretNumber) {
cout << "Too high! Try again." << endl;
} else if (guess < secretNumber) {
cout << "Too low! Try again." << endl;
} else {
cout << "Congratulations! You guessed it in " << attempts << " attempts." << endl;
}
} while (guess != secretNumber);
return 0;
}
Code output
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 50
Too low! Try again.
Enter your guess: 75
Too high! Try again.
Enter your guess: 63
Too high! Try again.
Enter your guess: 57
Too low! Try again.
Enter your guess: 60
Congratulations! You guessed it in 5 attempts.